/**
 * Copyright 2012 Huy HCQ
 */

package pit.com.ordermobilesystem.http;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JSONUtils {

  private static final boolean DEBUG =false;
  private static final Logger LOG = Logger.getLogger(JSONUtils.class.getCanonicalName());

  /**
   * Takes a parser, a json string, and returns a IModel type.
   */
  public static HttpModel consume(Parser<? extends HttpModel> parser, String content) throws HttpApiException, IOException {

    if (DEBUG) {
      LOG.log(Level.FINE, "http response: " + content);
    }

    try {
      // The v1 API returns the response raw with no wrapper. Depending on the
      // type of API call, the content might be a JSONObject or a JSONArray.
      // Since JSONArray does not derive from JSONObject, we need to check for
      // either of these cases to parse correctly.
      if (content.startsWith("[")) {
        JSONArray jsarr = new JSONArray(content);
        return parser.parse(jsarr);
      } else {
        JSONObject json = new JSONObject(content);
        if (json.has("error"))
          throw new HttpApiException(json.getString("error"));
        else if (json.keys().hasNext())
          return parser.parse(json);
        else
          throw new HttpApiException("Error parsing JSON response, object had no single child key.");
      }
    } catch (JSONException ex) {
      throw new HttpApiException("Error parsing JSON response: " + ex.getMessage());
    }
  }
}